package com.example.saiweisi.service.impl.userService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.saiweisi.controller.dto.UserDTO;
import com.example.saiweisi.controller.request.AddUserRequest;
import com.example.saiweisi.controller.request.UserLoginRequest;
import com.example.saiweisi.exception.ServiceException;
import com.example.saiweisi.mapper.userMapper.UserMapper;
import com.example.saiweisi.model.*;
import com.example.saiweisi.service.interf.IUserService;
import com.example.saiweisi.service.interf.IValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserService implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private JavaMailSender javaMailSender;
    @Autowired
    private IValidation validationService;
    @Value("${spring.mail.username}")
    private String from;

    private String registercode;
    private Date registertime;
    private String updatecode;
    private Date updatetime;
    @Override
    public UserDTO login(UserLoginRequest request) {
        UserDTO userDTO = new UserDTO();
        User user = userMapper.login(request);
        if (user == null) {
            throw new ServiceException("用户名或密码错误！");
        }
        BeanUtils.copyProperties(user, userDTO);
        return userDTO;
    }

    @Override
    public UserDTO loginByEmail(UserLoginRequest request) {
        UserMail userMail = userMapper.loginByEmail(request);
        if (userMail == null) {
            throw new ServiceException("验证码错误！");
        }
        if (validationService.getTimeByEmail(request.getEmail()).compareTo(new Date()) < 0) {
            throw new ServiceException("该邮箱验证码已经过期，请重新发送");
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userMail, userDTO);
        return userDTO;
    }

    //发送邮箱验证码
    @Override
    public void sendCode(String email) {
        Date date = new Date();
        //先在数据库中查询是否有此邮箱
        if (validationService.getByEmail(email) == 0) {
            throw new ServiceException("该邮箱未注册，请先注册后再登录");
        }
        if (validationService.getTimeByEmail(email) == null || validationService.getTimeByEmail(email).compareTo(date) < 0) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setSubject("【塞维斯洗衣馆】邮箱验证");
            String code = RandomUtil.randomNumbers(4);//随机生成一个四位数字验证码
            message.setText("您的邮箱验证码是：" + code + "，有效期三分钟，如非您本人操作，请忽略此条邮件。");
            message.setSentDate(date);
            message.setTo(email);
            javaMailSender.send(message);
            validationService.saveCode(email, code, DateUtil.offsetMinute(date, 3));
        } else {
            throw new ServiceException("该邮箱验证码尚未过期，请勿重复发送");
        }
    }

    @Override
    public Long register(UserLoginRequest request) {
        if(!(request.getCode().equals(registercode))){
            throw new ServiceException("验证码错误");
        }
        if (registertime.compareTo(new Date()) < 0) {
            throw new ServiceException("该邮箱验证码已经过期，请重新发送");
        }
        User user=new User();
        user.setUserPassword(request.getUserPassword());
        //遍历数据库，将最大的 num加一 赋值给新用户，来达到生成唯一标识符的目的
        long s=1;
        List<User> list=userMapper.getAllUser();
        for (User a:list
        ) {
            if(a.getUserNum()>s){
                s=a.getUserNum();
            }
        }
        user.setUserNum(s+1);
        userMapper.addUser(user);
        Validation validation=new Validation();
        validation.setEmail(request.getEmail());
        validation.setId(user.getUserId());
        userMapper.save(validation);
        return user.getUserNum();
    }

    @Override
    public Long add(AddUserRequest request) {
        User user=new User();
        //遍历数据库，将最大的 num加一 赋值给新用户，来达到生成唯一标识符的目的
        long s=1;
        List<User> list=userMapper.getAllUser();
        for (User a:list
        ) {
            if(a.getUserNum()>s){
                s=a.getUserNum();
            }
        }
        user.setUserNum(s+1);
        user.setUserAddress(request.getUserAddress());
        user.setUserName(request.getUserName());
        user.setUserTel(request.getUserTel());
        user.setUserPassword("111");
        userMapper.addUser001(user);
        return user.getUserNum();
    }
    @Override
    public void sendCodeToRegister(String email) {
        Date date = new Date();
        //先在数据库中查询是否有此邮箱
        if (validationService.getByEmail(email) == 1) {
            throw new ServiceException("该邮箱已经存在，请前往登录");
        }
        if (!(registertime == null || registertime.compareTo(date) < 0)){
            throw new ServiceException("该邮箱验证码尚未过期，请勿重复发送");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject("【塞维斯洗衣馆】邮箱验证");
        registercode = RandomUtil.randomNumbers(4);//随机生成一个四位数字验证码
        message.setText("您的邮箱验证码是：" + registercode + "，有效期三分钟，如非您本人操作，请忽略此条邮件。");
        message.setSentDate(date);
        message.setTo(email);
        javaMailSender.send(message);
        registertime=DateUtil.offsetMinute(date,3);
    }

    @Override
    public void sentEmailCodeToForgetPassword(String email, Integer userNum) {
        Date date = new Date();
        if(userMapper.getuserNum(userNum)==0){
            throw new ServiceException("没有找到该账号");
        }
        if(userMapper.getuserByuserNumAndemail(email,userNum)==0){
            throw new ServiceException("邮箱输入有误，请仔细核对后重新输入");
        }
        if (validationService.getTimeByEmail(email) == null || validationService.getTimeByEmail(email).compareTo(date) < 0) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setSubject("【塞维斯洗衣馆】邮箱验证");
            String code = RandomUtil.randomNumbers(4);//随机生成一个四位数字验证码
            message.setText("您的邮箱验证码是：" + code + "，有效期三分钟，如非您本人操作，请忽略此条邮件。");
            message.setSentDate(date);
            message.setTo(email);
            javaMailSender.send(message);
            validationService.saveCode(email, code, DateUtil.offsetMinute(date, 3));
        } else {
            throw new ServiceException("该邮箱验证码尚未过期，请勿重复发送");
        }

    }

    @Override
    public void forgetPassword(UserLoginRequest request) {
        if(userMapper.getuserNum((int) request.getUserNum())==0){
            throw new ServiceException("没有找到该账号");
        }
        if(userMapper.getuserByuserNumAndemail(request.getEmail(), (int) request.getUserNum())==0){
            throw new ServiceException("邮箱输入有误，请仔细核对后重新输入");
        }
        UserMail userMail = userMapper.loginByEmail(request);
        if (userMail == null) {
            throw new ServiceException("验证码错误！");
        }
        if (validationService.getTimeByEmail(request.getEmail()).compareTo(new Date()) < 0) {
            throw new ServiceException("该邮箱验证码已经过期，请重新发送");
        }
        userMapper.updatePassword(request.getUserNum(),request.getUserPassword());
    }

    @Override
    public void saveUserInfo(User user) {
        userMapper.saveUserInfo(user);
    }

    @Override
    public void sendCodeToUpdateEmail(String email) {
        Date date = new Date();
        //先在数据库中查询是否有此邮箱
        if (validationService.getByEmail(email) == 1) {
            throw new ServiceException("该邮箱已被使用");
        }
        if (!(updatetime == null || updatetime.compareTo(date) < 0)){
            throw new ServiceException("该邮箱验证码尚未过期，请勿重复发送");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject("【塞维斯洗衣馆】邮箱验证");
        updatecode = RandomUtil.randomNumbers(4);//随机生成一个四位数字验证码
        message.setText("您的邮箱验证码是：" + updatecode + "，有效期三分钟，如非您本人操作，请忽略此条邮件。");
        message.setSentDate(date);
        message.setTo(email);
        javaMailSender.send(message);
        updatetime=DateUtil.offsetMinute(date,3);
    }

    @Override
    public void updateEmail(UserLoginRequest request) {
        if(!(request.getCode().equals(updatecode))){
            throw new ServiceException("验证码错误");
        }
        if (updatetime.compareTo(new Date()) < 0) {
            throw new ServiceException("该邮箱验证码已经过期，请重新发送");
        }
        userMapper.updateEmail(request);
    }

    @Override
    public int searchByuserNum(String userNum) {
        int userId = 0;
        try {
            userId =  userMapper.searchByuserNum(userNum);
        } catch (Exception e){
        }
        return userId;
    }


}
